package com.jcj.pojoprotobuf;

import com.google.protobuf.ByteString;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 测试基于Protobuf的实体对象传输
 */
@ChannelHandler.Sharable
public class HandlerClientPB extends SimpleChannelInboundHandler<Object> {


    /**
     * 处理接收到的消息
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {

        //读取消息,得到反序列后的实体对象
        InformationProto.Information information = (InformationProto.Information) msg;
        System.out.println("具体的数据内容:" + information.getContent());

        byte[] header = information.getHeader().toByteArray();
        System.out.println("header:" + ByteBufUtil.hexDump(header).toUpperCase());

    }

    /**
     * 处理I/O事件的异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();//关闭当前Channel的连接
    }

    /**
     * 建立连接后该channelActive()方法只会被调用一次,这里的逻辑:建立连接后,字节序列被发送到服务器,编码格式是utf-8
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        //发送自定义协议格式的消息
        byte[] header = new byte[]{(byte) 0x5A, (byte) 0x5A};
        byte[] msgtype = new byte[]{(byte) 0x01};

        InformationProto.Information information = InformationProto.Information.newBuilder()
                .setHeader(ByteString.copyFrom(header))
                .setMsgtype(ByteString.copyFrom(msgtype))
                .setPersonnum(178)
                .setPrice(10015.78f)
                .setContent("你好,天王盖地虎!")
                .build();

        ctx.writeAndFlush(information);

    }
}






























































